package com.dwjm.shop.Jbp.client;

import com.dwjm.shop.Jbp.Goods.Goods;
import com.dwjm.shop.Jbp.utils.ConnectionDatabaseForSQLSeverUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ConsumerDaoImpl implements ConsumerDao {
    Connection connection = null;

    PreparedStatement pstmt = null;

    ResultSet rset = null;

    public ConsumerDaoImpl() {
        connection = ConnectionDatabaseForSQLSeverUseJdbc.getConnection();
    }

    @Override
    public List<Goods> getAllConsumer() {
        List<Goods> goodList = new ArrayList<>();
        try {
            pstmt = connection.prepareStatement("SELECT id,title,price,descr,img,state,mid FROM t_goods where state=0");
            rset = pstmt.executeQuery();
            while (rset.next()) {
                goodList.add(new Goods(
                        rset.getInt("id"),
                        rset.getString("title"),
                        rset.getBigDecimal("price"),
                        rset.getString("descr"),
                        rset.getString("img"),
                        rset.wasNull() ? 0 : rset.getInt("state"),
                        rset.wasNull() ? 0 : rset.getInt("mid")));
            }
            return goodList;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //注册
    @Override
    public int addConsumer(String account, String password) {
        try {
            pstmt = connection.prepareStatement("INSERT INTO t_consumer(account,password) VALUES(?,?)");
            pstmt.setString(1, account);
            pstmt.setString(2, password);
            int i = pstmt.executeUpdate();
            return i;


        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
//登录
    @Override
    public Consumer login(String account, String password) {
        try {
            pstmt = connection.prepareStatement("select  account,password from t_consumer where account=? and password=?");
            pstmt.setString(1, account);
            pstmt.setString(2, password);
            Consumer consumer = new Consumer();
            rset = pstmt.executeQuery();
            if (rset.next()) {
                consumer.setAccount(rset.getString("account"));
                consumer.setPassword(rset.getString("password"));
                return consumer;
                }
            return consumer;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
